package com.huige.controller;

import com.huige.pojo.Emp;
import com.huige.pojo.Result;
import com.huige.service.EmpService;
import com.huige.utils.JwtUtils;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Hashtable;
import java.util.Map;

/**
 * ClassName: LoginController
 * Package: com.huige.controller
 * Description:
 *
 * @Author 朱志辉
 * @Create 2024/5/6 14:23
 * @Version 1.0
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;

    /**
     * 登录设置
     *
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        log.info("员工登录：{}", emp);
        Emp e = empService.login(emp);

        //登录成功，生成令牌并下发令牌
        if (e != null) {
            Map<String, Object> claims = new Hashtable<>();
            claims.put("id", e.getId());
            claims.put("name", e.getName());
            claims.put("userName", e.getUsername());

            // 使用JwtUtils工具生成JWT令牌
            String jwt = JwtUtils.generateJwt(claims);//jwt包含了当前登录的员工信息

            //返回令牌
            return Result.success(jwt);
        }

        //登录失败，返回错误信息
        return e != null ? Result.success(e) : Result.error("用户名或密码错误");
    }
}
